import requests

from setting import URL_MAP


def fetch_platform_data(itemId, key):
    params = {'itemId': itemId}
    try:
        response = requests.get(URL_MAP[key], params=params, timeout=5, verify=False, headers={"Connection": "Close"})
        response.raise_for_status()
        return response.json()

    except Exception as e:
        # 请求失败
        return None


def concat_url(prod_id, plat_name):
    if plat_name == "淘宝":
        return "https://item.taobao.com/item.htm?id=" + prod_id
    elif plat_name == "京东":
        return "https://item.jd.com/" + prod_id + ".html"
    elif plat_name == "拼多多":
        return "https://mobile.yangkeduo.com/goods.html?goods_id=" + prod_id
    elif plat_name == "唯品会":
        return "https://detail.vip.com/detail-{}-0.html".format(prod_id)
    else:
        return None


def extract_title_img_name_url(item, platform):
    try:
        if platform == '淘宝':
            item = item['result_list'][0]
            return {
                'title': item['item_basic_info'].get('title'),
                "productImage": item['item_basic_info'].get('pict_url'),
                "productName": item['item_basic_info'].get('title'),
                "productUrl": item['item_basic_info'].get('click_url'),
            }
        elif platform == '京东':
            item = item['data'][0]
            return {
                'title': item.get('skuName'),
                "productImage": item['imageInfo']['imageList'][0]["url"],
                "productName": item.get('skuName'),
                "productUrl": item['materialUrl'],
            }
        elif platform == '拼多多':
            item = item['goods_details'][0]

            return {
                'title': item.get('goods_name'),
                "productImage": item.get("goods_image_url"),
                "productName": item.get('goods_name'),
                # "productUrl": item.get('goods_url'),
                "productUrl": None,
            }
        elif platform == '唯品会':
            item = item['result'][0]
            return {
                'title': item.get('goodsName'),
                "productImage": item.get("goodsMainPicture"),
                "productName": item.get('goodsName'),
                "productUrl": item.get('destUrl'),
            }
        # 其它平台解析
        else:
            return {}
    except Exception as e:
        # 失败
        return {}
